﻿using System;

using Gonte.Xml.Serialization;
using Gonte.Reflection;
using System.Diagnostics;
using System.Xml.Serialization;

namespace Gonte
{
    internal class ProxyObjectDeserializer
        : XmlObjectDeserializer
    {
        public ProxyObjectDeserializer(Object @object)
            : base(@object)
        {
        }

        protected override bool OnElement()
        {
            IncrementLevel();

            string elementName = Reader.LocalName;

            ProxyObject proxyObject = (ProxyObject)object_;

            if (string.IsNullOrEmpty(rootElementName_)) // Root element
            {
                VerifyElementNameMatchesObjectType(elementName);
                rootElementName_ = elementName;

                // Create the child object
                proxyObject.Name = Reader["Name"];
                proxyObject.Type = Reader["Type"];

                proxyObject.Object = ObjectFactory.CreateObject(proxyObject.Type);
                return false; // Do not process the attributes
            }

            // Get the deserializer
            XmlObjectDeserializer deserializer = XmlObjectDeserializer.GetDeserializer(proxyObject.Object);

            // Create and populate the context
            XmlSerializationContext context = new XmlSerializationContext();
            context.Parent = object_;
            //context.PropertyName = propertyName;
            //context.Attributes = properties.GetCustomAttributes(propertyName, null, false);

            // Deserialize the child object
            proxyObject.Object = deserializer.Deserialize(Reader, context);

            // Set the value back
            //proxyObject.Object = child;

            if (Reader.IsEmptyElement)
            {
                return false; // Do not process attributes
            }

            return true; // Process attributes
        }
    }
}
